from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect, render
from rest_framework import serializers, viewsets
from rest_framework.response import Response
from rest_framework import status
from Serializer import BindSerializer
from models import HuaweiCloud, BindServer
from settings import KEY_NAME
import re
import time

from openstack import connection
from openstack.dns.v2.recordset import Recordset
from openstack.dns.v2.zone import Zone

# create connection
username = "cangoitadmin"
password = "op17afv71$n"
projectId = "d19c236bc28a403788989e19b4d2e055"  # tenant ID
userDomainId = "875611680d1c43d1b1966f656e1c3342"  # user account ID
auth_url = "https://iam.cn-east-2.myhuaweicloud.com/v3"  # endpoint url

conn = connection.Connection(auth_url=auth_url,
                             user_domain_id=userDomainId,
                             project_id=projectId,
                             username=username,
                             password=password)


def delete_recordset(conn,zoneid,recordid):
    zone = Zone(id=zoneid)
    recordset = Recordset(id=recordid)
    delete_status = conn.dns.delete_recordset(zone, recordset)
    print delete_status
    return delete_status


@login_required()
def view_sync_huaweicloud(request, dns_server, zone_name):
    username = "cangoitadmin"
    password = "op17afv71$n"
    projectId = "d19c236bc28a403788989e19b4d2e055"  # tenant ID
    userDomainId = "875611680d1c43d1b1966f656e1c3342"  # user account ID
    auth_url = "https://iam.cn-east-2.myhuaweicloud.com/v3"  # endpoint url

    conn = connection.Connection(auth_url=auth_url,
                                 user_domain_id=userDomainId,
                                 project_id=projectId,
                                 username=username,
                                 password=password)

    zone_array = {}
    this_server = get_object_or_404(BindServer, hostname=dns_server)
    try:
        zone_array = this_server.list_zone_records(zone_name)

    except:
        messages.error(request, "Unable to get zone list. A problem was encountered "
                                "decrypting your TSIG key. Ensure the key is correctly "
                                "specified in the Binder Database.")
    zoneid = HuaweiCloud.objects.get(zone_name=zone_name).zone_id
    recordsets = conn.dns.recordsets(zoneid)

    crecordlist = []
    recordlist = []
    for recordset in recordsets:
        records = {}
        recordname = re.sub(str('.' + recordset.zone_name), '', str(recordset.name))
        if recordset.type == "A":
            records["name"] = recordname
            records["record"] = recordset.records
            records["id"] = recordset.id
            recordlist.append(records)
            crecordlist.append(recordname)

    print crecordlist
    print recordlist

    dnslist = []
    for local in zone_array:
        if local["rr_type"] == "A":
            dnsrecord = local["rr_name"]
            dnslist.append(dnsrecord)

    createlist = list(set(dnslist).difference(set(crecordlist)))
    print createlist

    samelist = list(set(crecordlist) & (set(dnslist)))
    print samelist

### Create Function ####
    for local in zone_array:
        for clist in createlist:
            if clist == local["rr_name"]:
                setname = local["rr_name"] + "." + zone_name + "."
                print setname + "has been added to HuaweiCloud"
                dict = {
                        "name": setname,
                        "description": "",
                        "type": "A",
                        "ttl": 300,
                        "records": [
                            local["rr_data"]
                        ]
                    }
                dnsset = conn.dns.create_recordset(zoneid, **dict)
                print dnsset

    updatelist = []
    for name in samelist:
        for reco in recordlist:
            if name == reco["name"]:
                updatelist.append(reco)
    print updatelist


### Update Function #####
    for local in zone_array:
        for info in updatelist:
            if local["rr_name"] == info["name"] and local["rr_data"] != info["record"][0]:
                recordid = info["id"]
                delete_recordset(conn,zoneid,recordid)
                setname = local["rr_name"] + "." + zone_name + "."
                print setname + "has been added to HuaweiCloud"
                dict = {
                    "name": setname,
                    "description": "",
                    "type": "A",
                    "ttl": 300,
                    "records": [
                        local["rr_data"]
                    ]
                }
                dnsset = conn.dns.create_recordset(zoneid, **dict)
                print dnsset

    return redirect('zone_list',
                   dns_server=dns_server,
                   zone_name=zone_name)






                    # print createlist
    # # print createlist
    # # print updatelist

    # for local in zone_array:
    #     for clist in createlist:
    #         if local["rr_name"] == clist:
    #             setname = local["rr_name"] + "." + zone_name + "."
    #             print setname + "has been added to HuaweiCloud"
    #             dict = {
    #                 "name": setname,
    #                 "description": "",
    #                 "type": "A",
    #                 "ttl": 300,
    #                 "records": [
    #                     local["rr_data"]
    #                 ]
    #             }
    #
    #             dnsset = conn.dns.create_recordset(zoneid, **dict)
    #
    # for local in zone_array:
    #     for ulist in updatelist:
    #         if local["rr_name"] == ulist:
    #             setname = local["rr_name"] + "." + zone_name + "."
    #             print setname + "has been added to HuaweiCloud"
    #             dict = {
    #                 "name": setname,
    #                 "description": "",
    #                 "type": "A",
    #                 "ttl": 300,
    #                 "records": [
    #                     local["rr_data"]
    #                 ]
    #             }
    #
    #             dnsset = conn.dns.create_recordset(zoneid, **dict)

    # print recordlist

# elif local["rr_name"] != recordname:
#     print local["rr_name"] + '!!!!!' + recordname
#     setname = local["rr_name"] + "." + recordset.zone_name
#     print setname + "has been added to HuaweiCloud"
#     dict = {
#         "name" : setname,
#         "description": "",
#         "type": "A",
#         "ttl": 300,
#         "records": [
#             local["rr_data"]
#         ]
#     }
#     print dict
#     dnsset = conn.dns.create_recordset(zoneid,**dict)
#     print dnsset
# else:
#     print local["rr_name"] + '!!!!!' + recordname
